package com.ofps.web.service;

import com.ofps.common.core.domain.entity.SysDept;
import com.ofps.system.domain.SysUserPost;
import com.ofps.system.mapper.SysDeptMapper;
import com.ofps.system.mapper.SysUserPostMapper;
import com.ofps.system.service.ISysDeptService;
import com.ofps.system.service.impl.SysDeptServiceImpl;
import com.ofps.system.service.impl.SysPostServiceImpl;
import com.ofps.system.service.impl.SysRoleServiceImpl;
import com.ofps.web.manager.AsyncManager;
import com.ofps.web.manager.factory.AsyncFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ofps.common.constant.Constants;
import com.ofps.common.constant.UserConstants;
import com.ofps.common.core.domain.entity.SysUser;
import com.ofps.common.core.domain.model.RegisterBody;
import com.ofps.common.core.redis.RedisCache;
import com.ofps.common.exception.user.CaptchaException;
import com.ofps.common.exception.user.CaptchaExpireException;
import com.ofps.common.utils.MessageUtils;
import com.ofps.common.utils.SecurityUtils;
import com.ofps.common.utils.StringUtils;
import com.ofps.system.service.ISysConfigService;
import com.ofps.system.service.ISysUserService;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 注册校验方法
 *
 * @author ruoyi
 */
@Component
public class SysRegisterService {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysDeptServiceImpl deptService;

    @Autowired
    private SysRoleServiceImpl roleService;


    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody) {

        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword(), deptName = registerBody.getDeptName();
        Boolean type = registerBody.getType();

        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StringUtils.isEmpty(username)) {
            msg = "用户名不能为空";
        } else if (StringUtils.isEmpty(password)) {
            msg = "用户密码不能为空";
        } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            msg = "账户长度必须在2到20个字符之间";
        } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            msg = "密码长度必须在5到20个字符之间";
        }
        //企业校验
        else if (type && StringUtils.isEmpty(deptName)) {
            msg = "企业名称不能为空";

        } else if (type && deptService.isExistDept(deptName)) {
            msg = "注册企业' " + deptName + " '失败，注册企业名称已存在";
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username))) {
            msg = "保存用户' " + username + " '失败，注册账号已存在";
        } else {
            //添加用户
            SysUser sysUser = new SysUser();
            sysUser.setUserName(username);
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));

            //type = true 企业注册
            if (type) {
                //注册企业
                SysDept sysDept = new SysDept();
                //设置企业信息
                sysDept.setParentId(UserConstants.DEPT_PARENT_ID);  //parent_id
                sysDept.setAncestors(UserConstants.DEPT_ANCESTORS); //ancestors
                sysDept.setDeptName(deptName);//deptName
                sysDept.setOrderNum(UserConstants.DEPT_ORDER_NUM);
                sysDept.setLeader(username);
                sysDept.setStatus(UserConstants.NORMAL);
                sysDept.setDelFlag(UserConstants.NORMAL);
                sysDept.setCreateBy(UserConstants.DEPT_CREATE_BY);
                int regFlag = deptService.insertDept(sysDept);
                if (regFlag == 0) return "注册失败,请联系系统管理人员";
                else AsyncManager.me().execute(AsyncFactory.recordLogininfor(deptName, Constants.REGISTER,
                        MessageUtils.message("user.register.success")));

                Long deptId = deptService.selectDeptIdByName(deptName);
                sysUser.setDeptId(deptId);
            }


            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag) {
                return "注册失败,请联系系统管理人员";
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER,
                        MessageUtils.message("user.register.success")));
            }

            //分配角色
            Long userId = userService.selectIdByUserName(username);
            Long roleId = type ? UserConstants.ROLE_ENTERPRISE : UserConstants.ROLE_USER;
            roleService.insertAuthUsers(roleId, new Long[]{userId});

            //分配岗位
            List<SysUserPost> userPostList = new LinkedList<>();
            SysUserPost userPost = new SysUserPost();
            Long postId = type ? UserConstants.POST_ADMIN : UserConstants.POST_USER;
            userPost.setPostId(postId);
            userPost.setUserId(userId);
            userPostList.add(userPost);
            sysUserPostMapper.batchUserPost(userPostList);

        }

        return msg;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }

}